package com.wosai.teach.activity;

import java.io.File;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.wosai.teach.R;
import com.wosai.teach.cst.AppCst;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.ChooseHeadDialog;
import com.wosai.teach.dialog.NetAvaiableDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.User;
import com.wosai.teach.listener.ChooseHeadListener;
import com.wosai.teach.oss.OssManager;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.BitmapHelp;
import com.wosai.teach.utils.OtherUtils;
import com.wosai.teach.utils.PhotoUtils;

@SuppressWarnings("deprecation")
public class AppFragmentActivity extends BaseFragmentActivity implements
		OnClickListener {
	private FrameLayout mFlRoot;
	private RelativeLayout mRlBack;
	private RelativeLayout mRlRefresh;
	private RelativeLayout mRlHead;
	private RelativeLayout mRLshare;
	private RelativeLayout mRLpublish;
	private RelativeLayout mRlSearch;
	private TextView mTxtTitle;
	private RelativeLayout mRlMessage;
	private ProgressBar mPbProgress;
	private TextView mTxtCount;
	private MessageReceiver mMsgReceiver;
	private boolean mTipExit;
	private boolean mExit;
	private OnRefreshListener mRefreshListener;
	private OnBackListener mBackListener;
	private NetAvaiableDialog mNetAvaiableDialog;
	private OnShareListener mShareListener;
	private OnPublishListener mPublishListener;
	private OnSearchListener mSearchListener;

	private RelativeLayout mlayout_menu_login;
	private RelativeLayout mlayout_menu_mymessage;
	private RelativeLayout mlayout_menu_homeworkAndScore;
	private RelativeLayout mlayout_menu_cache;
	private RelativeLayout mlayout_menu_settings;
	private RelativeLayout mHeadTop;

	private DrawerLayout mDrawerLayout;
	private LinearLayout mSlideMenu;

	private BitmapUtils bitmapUtils;
	private User user;
	/**
	 * 用于判断之前是调用本体图片还是拍照
	 */
	private int used = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_base);
		user = db.findFirst(User.class);

		mHeadTop = (RelativeLayout) findViewById(R.id.head_top);

		// 返回
		mRlBack = (RelativeLayout) findViewById(R.id.base_id_back);
		mRlBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBackListener != null) {
					mBackListener.onBack();
					finish();
				} else {
					finish();
				}
			}
		});

		// 系统消息
		mRlMessage = (RelativeLayout) findViewById(R.id.base_id_message);
		mTxtCount = (TextView) findViewById(R.id.base_id_count);
		mRlMessage.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(BaseActivity.this,
				// MessageActivity.class);
				// startActivity(intent);
			}
		});

		// 分享
		mRLshare = (RelativeLayout) findViewById(R.id.base_id_share);
		mRLshare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mShareListener != null) {
					mShareListener.onShare();
				}
			}
		});

		// 发表（同学圈）
		mRLpublish = (RelativeLayout) findViewById(R.id.base_id_publish);
		mRLpublish.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPublishListener != null) {
					mPublishListener.onPublish();
				}
			}
		});

		// 搜索
		mRlSearch = (RelativeLayout) findViewById(R.id.base_id_search);
		mRlSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mSearchListener != null) {
					mSearchListener.onSearch();
				}
			}
		});

		// 进度
		mPbProgress = (ProgressBar) findViewById(R.id.base_id_progress);

		IntentFilter filter = new IntentFilter();
		filter.addAction(AppCst.MSG_ACTION);
		mMsgReceiver = new MessageReceiver();
		registerReceiver(mMsgReceiver, filter);

		// 标题
		mTxtTitle = (TextView) findViewById(R.id.base_id_title);

		// 刷新
		mRlRefresh = (RelativeLayout) findViewById(R.id.base_id_refresh);
		mRlRefresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mRefreshListener != null)
					mRefreshListener.onRefresh();
			}
		});

		// 头像
		mRlHead = (RelativeLayout) findViewById(R.id.base_id_head);
		mRlHead.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mDrawerLayout.openDrawer(mSlideMenu);

			}
		});

		new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			@SuppressLint("NewApi")
			public void onDrawerClosed(View view) {
				// getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			@SuppressLint("NewApi")
			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		// 内容
		mFlRoot = (FrameLayout) findViewById(R.id.base_id_root);

		// 无网络对话框
		mNetAvaiableDialog = new NetAvaiableDialog(AppFragmentActivity.this);
		showUserIcon();

		mlayout_menu_login = (RelativeLayout) findViewById(R.id.layout_menu_login);
		mlayout_menu_login.setOnClickListener(this);
		LinearLayout myInfoLl = (LinearLayout) findViewById(R.id.my_info_ll);
		myInfoLl.setOnClickListener(this);

		mlayout_menu_mymessage = (RelativeLayout) findViewById(R.id.layout_menu_message);
		mlayout_menu_homeworkAndScore = (RelativeLayout) findViewById(R.id.layout_menu_homeworkAndScore);
		mlayout_menu_cache = (RelativeLayout) findViewById(R.id.layout_menu_cache);
		mlayout_menu_settings = (RelativeLayout) findViewById(R.id.layout_menu_settings);
		mlayout_menu_mymessage.setOnClickListener(this);
		mlayout_menu_homeworkAndScore.setOnClickListener(this);
		mlayout_menu_cache.setOnClickListener(this);
		mlayout_menu_settings.setOnClickListener(this);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mSlideMenu = (LinearLayout) findViewById(R.id.slideMenu);
		changeSlideWidth();

		ViewUtils.inject(this);
	}

	/**
	 * 侧边框三分之二
	 */
	private void changeSlideWidth() {
		WindowManager wm = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		DrawerLayout.LayoutParams params = (LayoutParams) mSlideMenu
				.getLayoutParams();
		params.width = width * 3 / 4;
		mSlideMenu.setLayoutParams(params);
	}

	private void showUserIcon() {
		User user = db.findFirst(User.class);
		if (user != null && user.getIcon1() != null) {
			bitmapUtils = BitmapHelp.getBitmapUtils(this);
			// // 加载网络图片
			ImageView mHead1 = (ImageView) findViewById(R.id.base_id_mhead);
			ImageView mHead = (ImageView) findViewById(R.id.one);
			mHead.setOnClickListener(this);

			bitmapUtils.display(mHead, user.getIcon1());
			bitmapUtils.display(mHead1, user.getIcon1());

			TextView myInformation = (TextView) findViewById(R.id.my_information);
			myInformation.setText(user.getUserName());
			TextView myCode = (TextView) findViewById(R.id.my_code);
			myCode.setText(user.getLoginName());
		}

	}

	@Override
	protected void inject() {
		// 忽略
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 刷新未读数
		refreshMessage();
		showUserIcon();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onBackPressed() {
		if (mTipExit) {
			if (mExit) {
				finish();
			} else {
				mExit = true;
				AppUtil.showToast(this, R.string.main_exit);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						mExit = false;
					}
				}, 2000);
			}
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mMsgReceiver);
	}

	/**
	 * 
	 */
	@Override
	public void setContentView(int layoutResId) {
		View view = LayoutInflater.from(this).inflate(layoutResId, null);
		mFlRoot.addView(view);
	}

	/**
	 * 
	 */
	@Override
	public void setContentView(View view) {
		mFlRoot.addView(view);
	}

	/**
	 * 是否显示返回功能
	 * 
	 * @param enabled
	 */
	public void enableBack(boolean enabled) {
		if (enabled) {
			mRlBack.setVisibility(View.VISIBLE);
		} else {
			mRlBack.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示分享功能
	 * 
	 * @param enabled
	 */
	public void enableShare(boolean enabled) {
		if (enabled) {
			mRLshare.setVisibility(View.VISIBLE);
		} else {
			mRLshare.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示发表功能
	 * 
	 * @param enabled
	 */
	public void enablePublish(boolean enabled) {
		if (enabled) {
			mRLpublish.setVisibility(View.VISIBLE);
		} else {
			mRLpublish.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示系统消息
	 * 
	 * @param enabled
	 */
	public void enableMessage(boolean enabled) {
		if (enabled) {
			mRlMessage.setVisibility(View.VISIBLE);
			refreshMessage();
		} else {
			mRlMessage.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示进度条（圈）
	 * 
	 * @param enabled
	 */
	public void enableProgress(boolean enabled) {
		if (enabled) {
			mPbProgress.setVisibility(View.VISIBLE);
			refreshMessage();
		} else {
			mPbProgress.setVisibility(View.GONE);
		}
	}

	public void enableSearch(boolean enabled) {
		if (enabled) {
			mRlSearch.setVisibility(View.VISIBLE);
		} else {
			mRlSearch.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否有进度显示
	 */
	public boolean isProgress() {
		return mPbProgress.getVisibility() == View.VISIBLE;
	}

	/**
	 * 刷新未读数
	 */
	public void refreshMessage() {
		if (mRlMessage.getVisibility() == View.VISIBLE) {
			// MessageDao msgDao = new MessageDao(this);
			// int count = msgDao.getUnreadCount();
			// if (count > 0) {
			// mTxtCount.setVisibility(View.VISIBLE);
			// mTxtCount.setText(count + "");
			// } else {
			// mTxtCount.setVisibility(View.GONE);
			// }
		}
	}

	/**
	 * 设置标题
	 */
	public void setTopTitle(int resId) {
		mTxtTitle.setText(resId);
	}

	/**
	 * 设置标题
	 * 
	 * @param title
	 */
	public void setTopTitle(String title) {
		mTxtTitle.setText(title == null ? "" : title);
	}

	/***
	 * 是否显示标题栏
	 * 
	 * @param enabled
	 */
	public void enableShowHeadTop(boolean enabled) {
		if (enabled) {
			mHeadTop.setVisibility(View.VISIBLE);
		} else {
			mHeadTop.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示刷新功能
	 * 
	 * @param enabled
	 */
	public void enableRefresh(boolean enabled) {
		if (enabled) {
			mRlRefresh.setVisibility(View.VISIBLE);
		} else {
			mRlRefresh.setVisibility(View.GONE);
		}
	}

	/**
	 * 是否显示左上角头像功能
	 * 
	 * @param head
	 */
	public void headRefresh(boolean head) {
		if (head) {
			mRlHead.setVisibility(View.VISIBLE);
		} else {
			mRlHead.setVisibility(View.GONE);
		}
	}

	/**
	 * 监听返回事件
	 * 
	 * @param listener
	 */
	public void setOnBackListener(OnBackListener listener) {
		this.mBackListener = listener;
	}

	/**
	 * 监听刷新事件
	 * 
	 * @param listener
	 */
	public void setOnRefreshListener(OnRefreshListener listener) {
		this.mRefreshListener = listener;
	}

	/**
	 * 监听分享事件
	 * 
	 * @param listener
	 */
	public void setOnShareListener(OnShareListener listener) {
		this.mShareListener = listener;
	}

	/**
	 * 监听分享事件
	 * 
	 * @param listener
	 */
	public void setOnPublishListener(OnPublishListener listener) {
		this.mPublishListener = listener;
	}

	public void setOnSearchListener(OnSearchListener listener) {
		this.mSearchListener = listener;
	}

	/**
	 * 安Back键是否提示退出
	 * 
	 * @param enabled
	 */
	public void enableTipExit(boolean enabled) {
		mTipExit = enabled;
	}

	/**
	 * 显示无网络对话框
	 */
	public void showNetAvaiableDialog() {
		if (!mNetAvaiableDialog.isShowing()) {
			mNetAvaiableDialog.show();
		}
	}

	/**
	 * 
	 * @author zhenshui.xia
	 * 
	 */
	private class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (AppCst.MSG_ACTION.equals(intent.getAction())) {
				refreshMessage();
			}
		}

	}

	public interface OnBackListener {
		public void onBack();
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public interface OnShareListener {
		public void onShare();
	}

	public interface OnPublishListener {
		public void onPublish();
	}

	public interface OnSearchListener {
		public void onSearch();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_menu_login:
			User user = db.findFirst(User.class);
			if (user == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.one:
			changeIcon();
			break;
		case R.id.my_info_ll:
			User user2 = db.findFirst(User.class);
			if (user2 != null) {
				// 查看信息
				Intent intent = new Intent(this, InformationActivity.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.layout_menu_message: {
			// Intent it = new Intent(this, MyMessageActivity.class);
			Intent it = new Intent(this, NewsActivity.class);
			startActivity(it);
			System.out.println(" 我的消息 ");
			break;
		}
		case R.id.layout_menu_homeworkAndScore: {
//			startActivity(new Intent(this, ScoreActivity.class));
			startActivityForResult(new Intent(this, HomeworkAndScoreActivity.class), C.REQUEST_CODE_OPEN_SCORE);
			break;
		}
		case R.id.layout_menu_cache: {
			startActivity(new Intent(this, CacheActivity.class));
			break;
		}
		case R.id.layout_menu_settings: {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 显示选择对话框
	 */
	public void changeIcon() {
		ChooseHeadDialog choose = new ChooseHeadDialog(this);
		choose.init(new ChooseHeadListener() {

			@Override
			public void onNative() {
				Intent intentFromGallery = new Intent();
				intentFromGallery.setType("image/*"); // 设置文件类型
				intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
				used = C.PHOTO_REQUEST_GALLERY;
				startActivityForResult(intentFromGallery,
						C.PHOTO_REQUEST_GALLERY);
			}

			@Override
			public void onPhoto() {
				// 判断存储卡是否可以用，可用进行存储
				if (OtherUtils.hasSdcard()) {
					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
							.fromFile(new File(Environment
									.getExternalStorageDirectory(),
									C.IMAGE_FILE_NAME)));
					used = C.PHOTO_REQUEST_CAMERA;
					startActivityForResult(intentFromCapture,
							C.PHOTO_REQUEST_CAMERA);

				} else {
					Toast.makeText(getApplicationContext(), "存储卡不可用",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		choose.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case C.PHOTO_REQUEST_GALLERY: {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				used = C.PHOTO_REQUEST_GALLERY;
				crop(uri);
			}
			break;
		}

		case C.PHOTO_REQUEST_CUT: {
			// 从剪切图片返回的数据
			if (data != null) {
				String fileName = getFileName();
				Bitmap bitmap = data.getParcelableExtra("data");
				OssManager.getInstance().asyncUpload(bitmap, "head/", fileName,
						this);// /head/
			} else {
				if (used == C.PHOTO_REQUEST_GALLERY) {
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
					used = C.PHOTO_REQUEST_CAMERA;
					startActivityForResult(intentFromGallery,
							C.PHOTO_REQUEST_GALLERY);
				} else {
					if (OtherUtils.hasSdcard()) {
						Intent intentFromCapture = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(Environment
										.getExternalStorageDirectory(),
										C.IMAGE_FILE_NAME)));
						used = C.PHOTO_REQUEST_CAMERA;
						startActivityForResult(intentFromCapture,
								C.PHOTO_REQUEST_CAMERA);

					} else {
						Toast.makeText(getApplicationContext(), "存储卡不可用",
								Toast.LENGTH_SHORT).show();
						break;
					}
				}
			}
			break;
		}

		case C.PHOTO_REQUEST_CAMERA: {
			if (resultCode == -1) {
				File temp = new File(Environment.getExternalStorageDirectory()
						+ "/head.jpg");
				used = C.PHOTO_REQUEST_CAMERA;
				crop(Uri.fromFile(temp));// 裁剪图片
			}

			break;
		}
		default:
			break;

		}
	}

	private String getFileName() {
		Date dd = new Date();
		long time = dd.getTime();
		String fileName = time + "_" + user.getUserId() + ".jpg";
		return fileName;
	}

	/**
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");

		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
			String url = PhotoUtils.getPath(this, uri);
			intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
		} else {
			intent.setDataAndType(uri, "image/*");
		}
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", false);// 不取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, C.PHOTO_REQUEST_CUT);
	}

	private int UPDATE_HEAD = 1;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_HEAD) {
				HttpUtils http = new HttpUtils();
				String url = C.HTTP_USER_INFO_UPDATE;
				RequestParams params = new RequestParams();

				String path = msg.getData().getString("path");

				url = url.replace("{userId}", user.getUserId() + "");

				User user1 = new User();
				user1.setUserId(user.getUserId());
				user1.setIcon1(path);
				String jsonStr = JSON.toJSONString(user1);

				params.addBodyParameter("content", jsonStr);

				http.send(HttpMethod.POST, url, params,
						new RequestCallBack<String>() {

							@Override
							public void onSuccess(
									ResponseInfo<String> responseInfo) {
								if (OtherUtils.CheckNull(responseInfo.result)) {
									return;
								}
								JsonResult jr = JSON.parseObject(
										responseInfo.result, JsonResult.class);
								if (jr.getResult() == 0) {
									User user = JSON.parseObject(jr.getObject()
											.toString(), User.class);
									if (user == null) {
										return;
									}
									db.deleteAll(Selector.from(User.class)
											.where("userId", "=",
													user.getUserId()));
									db.save(user);
									showUserIcon();
								}
							}

							@Override
							public void onFailure(HttpException error,
									String msg) {
								Toast.makeText(getApplicationContext(),
										"访问失败" + error.fillInStackTrace(),
										Toast.LENGTH_SHORT).show();
								System.out.println("==================="
										+ error.fillInStackTrace());
							}

						});
			}
		}
	};

	@Override
	public void callBack(String str) {
		String path = C.OSS_URL + str;
		System.out.println("oss_path||" + path);
		Message msg = new Message();
		msg.what = UPDATE_HEAD;
		msg.getData().putString("path", path);
		handler.sendMessage(msg);
	}
	
	/**
	 * 关闭侧滑菜单
	 */
	public void closeMenu(){
		mDrawerLayout.closeDrawer(mSlideMenu);
	}
	/**
	 * 锁定侧滑菜单，让其无法打开
	 */
	public void lockMenu(){
		mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
	}
}
